package com.lipaluma.field.validator.impl.collections;
import java.lang.reflect.Array;
import java.lang.reflect.Field;
import java.util.Collection;
import java.util.List;

import com.lipaluma.annotations.validations.ValidateCollection;
import com.lipaluma.context.Context;
import com.lipaluma.exceptions.CsvParserProcessException;
import com.lipaluma.field.validator.ValidationError;
import com.lipaluma.field.validator.Validator;
import com.lipaluma.xml.validator.XmlValidator;

public class CollectionNotEmptyValidator implements Validator {

	@Override
	public boolean init(Context context, Field field) {
		ValidateCollection annotation = field.getAnnotation(ValidateCollection.class);
		return 	(annotation != null && annotation.notEmpty());
	}

	@Override
	public boolean init(Context context, Field field, XmlValidator xmlValidator) {
		return true;
	}

	@SuppressWarnings("unchecked")
	public boolean validate(Object value, List<ValidationError> errors) {
		if (value.getClass().isArray()) {
			if(Array.getLength(value) == 0) {
				errors.add(new ValidationError("The array was empty"));
				return false;
			}
			return true;
		}else if(Collection.class.isAssignableFrom(value.getClass())) {
			Collection<Object> values = (Collection<Object>)value;
			if(values.isEmpty()) {
				errors.add(new ValidationError("The collection was empty"));
				return false;
			}
			return true;
		} else
			throw new CsvParserProcessException("For the not empty validation, the value must be an array or a Collection. But it was "+value.getClass());
	}

}
